<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\utils;


use app\shop_admin\model\Distribution;
use app\shop_admin\model\Order;
use think\Exception;
use app\shop_admin\model\Meituan as MeituanModel;

class Meituan
{
    private $appkey;
    private $base_url;
    private $mallId;

    public function __construct()
    {
        global $user;
        $disrt = Distribution::where(['mall_id' => $user->mall_id, 'merchant_id' => $user->merchant_id])->find();
        if (!empty($disrt['config']['app_key'])) throw new Exception('配置信息为空！', HTTP_INVALID);
        $this->appkey = $disrt['config']['app_key'];
        $this->base_url = "https://peisongopen.meituan.com/api/";
        $this->mallId = $user->mall_id;
    }

    /**预发布订单
     * @throws Exception
     */
    public function advanceOrder(array $data)
    {
        $interface = "order/preCreateByShop";
        try {
            $url = $this->base_url . $interface;
            $res = $this->post_curl($url, $data);
            return [HTTP_SUCCESS, $res];
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), HTTP_UNAUTH);
        }
    }

    /**
     * 订单创建
     * @throws Exception
     */
    public function createByShop(array $data)
    {
        $interface = "order/createByShop";
        try {
            $url = $this->base_url . $interface;
            $res = $this->post_curl($url, $data);
            $res['data']['mall_id'] = $this->mallId;
            MeituanModel::create($res['data']);
            return [HTTP_SUCCESS, $res];
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), HTTP_UNAUTH);
        }
    }

    /**
     * 取消订单
     */
    public function order_delete(array $data)
    {
        $interface = "order/delete";
        try {
            $url = $this->base_url . $interface;
            $res = $this->post_curl($url, $data);
            return [HTTP_SUCCESS, $res];
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), HTTP_UNAUTH);
        }
    }

    /**
     * 订单状态回调
     */
    public function callback(array $data): array
    {
        $sign = $this->sign($data);
        if ($sign != $data['sign'])
            return [HTTP_CREATED, '签名不一致'];
        $up = MeituanModel::update($data,
            ['delivery_id' => $data['delivery_id'], 'order_id' => $data['order_id']],
            ['status', 'courier_name', 'courier_phone', 'cancel_reason_id', 'cancel_reason', 'predict_delivery_time']);
        if ($data['status'] = 20) Order::update(['status' => 3], ['id' => $data['order_id']]);
        if ($data['status'] = 50) Order::update(['status' => 8], ['id' => $data['order_id']]);
        if ($up != false) return [HTTP_SUCCESS, ['code' => 0]];
    }

    /**
     * 异常回调
     */
    public function abnormal_callback(array $data): array
    {
        $sign = $this->sign($data);
        if ($sign != $data['sign'])
            return [HTTP_CREATED, '签名不一致'];
        $up = MeituanModel::update(['delivery_id' => $data['delivery_id'], 'order_id' => $data['order_id']],
            ['exception_id', 'exception_code', 'exception_descr', 'exception_time']);

        if ($up != false)
            return [HTTP_SUCCESS, ['code' => 0]];

    }

    /**
     *查询订单状态
     */
    public function getOrderState(array $data)
    {
        $interface = "order/status/query";
        try {
            $url = $this->base_url . $interface;
            $res = $this->post_curl($url, $data);
            return [HTTP_SUCCESS, $res];
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), HTTP_UNAUTH);
        }
    }

    /**
     * 查询门店信息
     */
    public function shop(array $data)
    {
        $inf = "shop/query";
        try {
            $url = $this->base_url . $inf;
            $res = $this->post_curl($url, $data);
            return [HTTP_SUCCESS, $res];
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), HTTP_UNAUTH);
        }
    }

    /**curl 请求美团接口
     * @param $url
     * @param $data
     * @return bool|string
     */
    public
    function post_curl($url, $data)
    {
        $data['version'] = 1.0;
        $data['timestamp'] = time();
        $data['appkey'] = $this->appkey;
        $data['sign'] = $this->sign($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    /**构造签名sign
     * @param array $data
     * @return string
     */
    private
    function sign(array $data)
    {
        sort($data);
        $str = "";
        foreach ($data as $k => $v) {
            if ($k == "sign" || empty($v)) continue;
            $str .= $k . $v;
        }
        return strtolower(sha1($str));
    }


}